package edu.gyc.producer.consumer;

import java.util.concurrent.TimeUnit;

class MyThread extends Thread {
    private String name;
    private Object co;

    public MyThread(String name, Object o) {
        this.name = name;
        this.co = o;
    }

    @Override
    public void run() {
        System.out.println(name + " is waiting.");
        try {
            synchronized (co) {
                co.wait();
            }
            System.out.println(name + " has been notified.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class WaitAndNotify {
    public static void main(String[] args) {
        Object co = new Object();
        System.out.println(co);
 
        for (int i = 0; i < 5; i++) {
            MyThread t = new MyThread("Thread" + i, co);
            t.start();
        }
 
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("-----Main Thread notify-----");
            synchronized (co) {
                //notify可能会导致死锁，而notifyAll则不会,当调度多个线程时用notifyAll
               co.notify();
             //   co.notifyAll();
            }
 
            TimeUnit.SECONDS.sleep(2);
            System.out.println("Main Thread is end.");
 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 

}
 
